//
//  PhotoAlbumUtils.swift
//  ECU
//
//  Created by 张坤 on 2022/5/7.
//

import UIKit
import Photos
public struct PhotoAlbumUtils {
    public enum PVMAlbumType{
        ///紧急录影视频
        case PVM_U
        ///普通录影视频
        case PVM_V
        ///照片
        case PVM
        var name:String{
            switch self {
            case .PVM_U:
                return "PVM+U"
            case .PVM_V:
                return "PVM+V"
            case .PVM:
                return "PVM+"
            }
        }
    }
    public static func requestAuthorization(){
        if #available(iOS 14, *) {
            PHPhotoLibrary.requestAuthorization(for: PHAccessLevel.readWrite) { status in
                PhotoAlbumUtils.requestAuthorizationHandler(status: status)
            }
        } else {
            PHPhotoLibrary.requestAuthorization { status in
                PhotoAlbumUtils.requestAuthorizationHandler(status: status)
            }
        }
        
    }
    static private func requestAuthorizationHandler(status: PHAuthorizationStatus) {
        switch status {
        case .notDetermined:
            print("用户尚未就此应用程序做出选择")
        case .restricted:
            print("此应用程序未被授权访问照片数据。")
        case .denied:
            print("用户明确拒绝此应用程序访问照片数据。")
        case .authorized:
            print("用户已授权此应用程序访问照片数据。")
            PhotoAlbumUtils.createPVMPhotoAlbum()
        case .limited:
            print("用户已授权此应用程序访问有限的照片库")
        @unknown default:
            fatalError()
        }
    }
    static private func createPVMPhotoAlbum(){
        let albumName1:PVMAlbumType = .PVM_U
        let albumName2:PVMAlbumType = .PVM_V
        let albumName3:PVMAlbumType = .PVM
        if (fetchAssetCollectionForAlbum(with: albumName1) == nil) {
            PhotoAlbumUtils.createAlbum(title: albumName1.name)
        }
        if (fetchAssetCollectionForAlbum(with: albumName2) == nil) {
            PhotoAlbumUtils.createAlbum(title: albumName2.name)
        }
        if (fetchAssetCollectionForAlbum(with: albumName3) == nil) {
            PhotoAlbumUtils.createAlbum(title: albumName3.name)
        }
        print("相册创建成功")
    }
    static private func createAlbum(title:String) {
        PHPhotoLibrary.shared().performChanges({
            PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: title)   // create an asset collection with the album name
        }) { success, error in
            if success {
                print("创建\(title)相册成功")
            } else {
                print("error \(error as Any)")
            }
        }
    }
    
    static func fetchAssetCollectionForAlbum(with pvmAlbum:PVMAlbumType) -> PHAssetCollection? {
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "title = %@", pvmAlbum.name)
        let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
        
        if let _: AnyObject = collection.firstObject {
            return collection.firstObject
        }
        return nil
    }
    
    static func save(with assetCollection: PHAssetCollection,image: UIImage) {
        
        PHPhotoLibrary.shared().performChanges({
            let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
            let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset
            let albumChangeRequest = PHAssetCollectionChangeRequest(for: assetCollection)
            let enumeration: NSArray = [assetPlaceHolder!]
            albumChangeRequest!.addAssets(enumeration)
            
        }, completionHandler: nil)
    }
}
